
local Reagents =
{
  DRUID = 
    { 
      { id = 44605, nStack = 1 },
      { id = 44614, nStack = 1 }
    },
  MAGE =
    {
      { id = 17020, nStack = 1 },
      { id = 17031, nStack = 1 },
      { id = 17032, nStack = 1 }
    },
  WARLOCK=
    {
      { id = 16583, nStack = 1 }
    },
  PRIEST =
    {
      { id = 44615, nStack = 1 }
    },
  ROGUE =
    {
      { id = 43233, nStack = 1 },
      { id = 43231, nStack = 1 },
      { id = 43235, nStack = 1 },
      { id = 43237, nStack = 1 },
      { id = 5237, nStack = 1 },
      { id = 3775, nStack = 1 }
    },
  SHAMAN =
    {
      { id = 17030, nStack = 1 }
    },
  HUNTER =
    {
    },
  PALADIN =
    {
      { id = 21177, nStack = 1 },
      { id = 17033, nStack = 1 }
    },
  WARRIOR =
    {
    },
  DEATHKNIGHT =
    {
      { id = 37201, nStack = 1 }
    }
};

function FormatMoney(money)
  local G = floor(money / 10000);
  local S = floor((money % 10000) / 100);
  local C = money % 100;

  if (G > 0) then 
    return ""..G.."|cFFFFFF00g|r"..S.."|cFFC0C0C0s|r"..C.."|cFFC08000c|r"; 
  elseif (S > 0) then 
    return ""..S.."S"..C.."C";
  else
    return C.."C";
  end
end

local _, class=UnitClass("player");

function BuyReagent()
  local items = Reagents[class];

--No action with SHIFT pressed
  if (IsShiftKeyDown()) then
    return;
  end

--Search for item:Exist->Buy it->Print msg
  for i = 1,#items do
    local ItemName = GetItemInfo(items[i].id);
    local bAccount = 0;
    local mInfo, mPrice;

    if ItemName == nil then 
      print("|cFF800000BuyReagent: Item "..items[i].id.." is not in local cache.|r");
    else
      for j = 1,GetMerchantNumItems() do
        mInfo, _, mPrice = GetMerchantItemInfo(j);
  
        if ((mInfo) and (mInfo:find(ItemName))) then
          local mMaxStack=GetMerchantItemMaxStack(j);
          local t = items[i].nStack * mMaxStack - GetItemCount(ItemName);
          if (t > 0) then
            for k=1,ceil(t / mMaxStack) do
              local count = floor(t / mMaxStack)~=0 and mMaxStack or t;
  
              BuyMerchantItem(j, count);
              t = t - mMaxStack;
              bAccount = bAccount + count;
            end;
          end
          break;
        end
      end
      if (bAccount > 0) then
        print("BuyReagent: Bought ["..ItemName.."]x"..bAccount.." ("..FormatMoney(bAccount*mPrice)..")");
      end
    end
  end
end

local BRFrame =  CreateFrame("Frame");
BRFrame:RegisterEvent("MERCHANT_SHOW");
BRFrame:SetScript("OnEvent", function(_, event, ...) if (event == "MERCHANT_SHOW") then BuyReagent();end end);
